 package myjavaapplication1;

   import java.io.*;
   import java.util.*;
   import gnu.io.*;

    public class ReadCommPortT implements SerialPortEventListener {

      static CommPortIdentifier portId;
      static Enumeration portList;
      static InputStream inputStream;
      static OutputStream outputStream;
      public SerialPort serialPort;
      public static String writeThis = "hello bite me please";
      public static String toFile = "";
      public static int filenumb = 0;
      public static int tries = 3;
      public static int wait = 10;
      public static int comnum=1;
      public static int count = 0;
      public static int MAX_RECIEVE_SIZE = 250;

       public ReadCommPortT(int com)
      {
         comnum=com;

      }


       public void setStuff(int Tries, int Wait, String s) {
         tries = Tries;
         wait = Wait;
         writeThis = s;

      }

       public String readData() {
         String ret = "ahh";
         count = 0;
         boolean portFound = false;
         String str=""+comnum;
         String defaultPort = "COM"+str;
         System.out.println(defaultPort);
         portList = CommPortIdentifier.getPortIdentifiers();

         while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
               if (portId.getName().equals(defaultPort)) {
                  System.out.println("Found port: " + defaultPort);
                  portFound = true;
                  ret= buildSerialPort();
               }
            }
         }
         if (!portFound) {
            System.out.println("port " + defaultPort + " not found.");
         }
         return ret;
      }

       public String buildSerialPort() {
         try {
            try {
               filenumb = 0;
               while (new File("rx" + filenumb + ".txt").exists()) //consecutively adds .txt files
               {
                  filenumb++;
               }
            }
                catch (Exception e) {
               }

            serialPort = (SerialPort) portId.open("ReadCommPort", 1);
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();
            serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            serialPort.notifyOnDataAvailable(true);

            serialPort.addEventListener(this);

         //   for (int j = 0; j < tries; j++) {
          //   return write();
         /*             wait(wait);
            }
         */
         }
             catch (Exception e) {
               e.printStackTrace();
            }
         return write();
       //  return "1";
      }

       public String write() {
         System.out.println("Writing \"" + writeThis + "\" to " + serialPort.getName());
         try {
            outputStream.write(writeThis.getBytes());
            outputStream.write(0x0D);
            outputStream.write(0x0A);
         }
             catch (Exception e) {
               System.out.println("COULD NOT WRITE");
            }

        //wait(5);
         wait(wait);
         System.out.println("This is toFile \r\n"+toFile);
        PrintToFile(toFile, filenumb);
         serialPort.close();
         return toFile;
      }

       @SuppressWarnings("unchecked")
       public void serialEvent(SerialPortEvent event) {

         switch (event.getEventType()) {
            case SerialPortEvent.BI:
               System.out.println("BI");
               break;
            case SerialPortEvent.OE:
               System.out.println("OE");
               break;
            case SerialPortEvent.FE:
               System.out.println("FE");
               break;
            case SerialPortEvent.PE:
               System.out.println("PE");
               break;
            case SerialPortEvent.CD:
               System.out.println("CD");
               break;
            case SerialPortEvent.CTS:
               System.out.println("CTS");
               break;
            case SerialPortEvent.DSR:
               System.out.println("DSR");
               break;
            case SerialPortEvent.RI:
               System.out.println("RI");
               break;
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
               System.out.println("OUTPUT_BUFFER_EMPTY");
               break;
            case SerialPortEvent.DATA_AVAILABLE:
               try {
                  int len = inputStream.available();
                    len=200; //radio can't hanlde above 200
                  count = count + len;
                  System.out.println(count);

                  char[] readBuffer = new char[len];
                    // processing data code..
                 // readBuffer[len+1]='\0';

                  System.out.println("Input Stream Avail: "+len);
                  for (int x = 0; x < len; x++) {

                     char temp = (char) inputStream.read();
                     System.out.print(temp);

                     readBuffer[x] = temp;
//                    long curr=System.currentTimeMillis();
//                    while(curr-System.currentTimeMillis()<10)
//                    {
//                     int a=0;
//                    }
                  }
                   System.out.println();

                  for (int x = 0; x < len; x++) {
                    // System.out.print(readBuffer[x]);
                     toFile += readBuffer[x];  ///THIS IS OUR STRING AND PUT THIS IN DOIT (cleanArray)

                  }

                  //inputStream.flush();

                  try {                                                     //I dont know if this Try-Catch actually does anything
                     serialPort.addEventListener(null);
                  }
                      catch (TooManyListenersException e) {
                        //e.printStackTrace();
                     }

               }
                   catch (IOException e) {
                     e.printStackTrace();
                     System.out.println("errorz line101ish");
                  }

               break;


         }
      }

       public static void main(String[] args) {  //main DOESN'T Work (8/5/11) Most Methods Work
         new ReadCommPortT(comnum).readData(); //1 is a place holder.
         System.out.println("main complete");
      }

       public void PrintToFile(String s, int n) {
         try {
            int num = 0;
            num = n;
            File file = new File("rx" + num + ".txt");
            PrintStream ps = new PrintStream(file);

            ps.print(s);
            ps.close();
         }
             catch (Exception e) {
               System.out.println("didnt do it; but add some handling code");
            }
      }

       public void wait(int n) {
         long t0, t1;
         long tCountDown=-1; //-1 = hasn't received stuff yet
         t0 = System.currentTimeMillis();
     do {

        if(count >=MAX_RECIEVE_SIZE){
              System.out.println("Overflow buffer");
              break;
                  }
       if(count >= 1) { 
          if(tCountDown<0)
              tCountDown=System.currentTimeMillis();
          else if (System.currentTimeMillis()-tCountDown>2000)
              break;
       }
        t1 = System.currentTimeMillis();
     } while (t1 - t0 < 1000 * n);
      }
   }



